import { defineStore } from 'pinia'
import { reqLogin, reqLogout } from '@/api/user/index.js'
import router from '@/router'
import { showToast } from 'vant'

export const useUserStore = defineStore('user', {
  state: () => ({
    username: localStorage.getItem('username') || ''
  }),
  actions: {
    async login(loginForm) {
      // 这里进行登录
      const result = await reqLogin(loginForm)
      if (result.code === 200) {
        this.username = loginForm.username
        localStorage.setItem('username', loginForm.username)
        showToast({type: "success", message: "登录成功"})
        return 'ok'
      } else {
        showToast({type: "fail", message: result.msg})
        return Promise.reject(new Error(result.msg))
      }
    },
    async logout() {
      // 清除用户信息
      const result = await reqLogout()
      if (result.code === 200) {
        this.username = ''
        localStorage.setItem('username', '')
        await router.push('/login')
      }
    }
  }
})
